public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if(root==null){
            root=new TreeNode(key);
            return true;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(key> cur.key){
                parent=cur;
                cur=cur.right;
            }else if(key< cur.key){
                parent=cur;
                cur=cur.left;
            }
            else{
                return false;
            }
        }

        TreeNode node=new TreeNode(key);
        if(key< parent.key){
            node=parent.left;
        }else{
            node=parent.right;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
    TreeNode cur=root;
    if(cur==null){
        return null;
    }
    while (cur!=null){
        if(cur.key==key){
            return cur;
        }else if(key< cur.key){
            cur=cur.left;
        }else{
            cur=cur.right;
        }

    }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(key< cur.key){
                parent=cur;
                cur=cur.left;
            }else if(key> cur.key){
                parent=cur;
                cur=cur.right;
            }else{
               break;
            }
        }
        if(cur==null){
            return false;
        }
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }else  if(cur==parent.left){
                parent.left=cur.right;
            }else {
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }else if(cur==parent.left){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
        }else {
            TreeNode t = cur.left;
            TreeNode tp = cur;
            while (t.right != null) {
                tp = t;
                t = t.right;
            }
            if (tp.right == t) {
                tp.right = t.left;
            }else {
                tp.left=t.left;
            }
        }
    return true;
    }


}